import { Component } from '@angular/core';
import {IonicPage, LoadingController, NavController, NavParams} from 'ionic-angular';
import {FileOpener} from "@ionic-native/file-opener";
import {File} from "@ionic-native/file";
import {FileTransfer, FileTransferObject} from "@ionic-native/file-transfer";
import {FileService} from "../../../services/native/file/file.service";
import {LocalStorageService} from "../../../services/native/local-storage/local-storage.service";

/**
 * Generated class for the FavoriteFilePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-favorite-file',
  templateUrl: 'favorite-file.html',
    providers:[FileOpener, FileTransfer, FileService, LocalStorageService]
})
export class FavoriteFilePage {

    filePath: string;
    // resourceId: string;

    mFileName: string;

    fileTransfer: FileTransferObject = this.transfer.create();

    now: number = 0;

  constructor(public navCtrl: NavController,
              private fileOpener: FileOpener,
              private file: File,
              private transfer: FileTransfer,
              public loadingCtrl: LoadingController,
              private fileService: FileService,
              public navParams: NavParams) {
  }

  ionViewDidLoad() {

  }

    downloadFile(fileName: string) {

        let loading = this.loadingCtrl.create({
            content:'downloading: 0%',
            dismissOnPageChange: false,
            // enableBackdropDismiss: true
        });
        loading.onDidDismiss(() => {
           console.log('dissmissed');
           // this.fileTransfer.abort();
        });
        loading.present();
        this.fileTransfer.onProgress(progressEvent => {
            if (progressEvent.lengthComputable) {
                console.log(progressEvent.loaded +'/' + progressEvent.total);
                this.now = progressEvent.loaded / progressEvent.total * 100;
            }
        });

        let mTimer = setInterval(() => {
            loading.setContent('downloading: '+Math.floor(this.now)+'%');
            if (this.now >= 99) {
                clearInterval(mTimer);
            }
        }, 300);

        this.mFileName = fileName;
        const url = 'http://10.248.36.33:8004/' + this.mFileName;
        // const url = 'http://10.248.37.254:8802/azure/v1/remove?resourceId=8a7482ea62236d84016223910f760005';
        this.fileTransfer.download(url, this.file.dataDirectory + this.mFileName).then((entry) => {
            console.log('download complete: ' + entry.toURL());
            this.filePath = entry.toURL();
            this.now = 0;
            loading.dismiss();
        }, (error) => {
            // handle error
            this.now = 0;
            loading.dismiss();
        });
    }


    downloadFile2(resourceId: string) {

        let loading = this.loadingCtrl.create({
            content:'downloading: 0%',
            dismissOnPageChange: false,
            // enableBackdropDismiss: true
        });
        loading.onDidDismiss(() => {
            console.log('dissmissed');
            // this.fileTransfer.abort();
        });
        loading.present();
        this.fileTransfer.onProgress(progressEvent => {
            // if (progressEvent.lengthComputable) {
            //     console.log(progressEvent.loaded +'/' + progressEvent.total);
            //     this.now = progressEvent.loaded / progressEvent.total * 100;
            // }
            console.log(progressEvent);
        });

        let mTimer = setInterval(() => {
            loading.setContent('downloading: '+Math.floor(this.now)+'%');
            if (this.now >= 99) {
                clearInterval(mTimer);
            }
        }, 300);

        // this.mFileName = fileName;
        // const url = 'http://10.248.36.33:8004/' + this.mFileName;
        // 8a74819e6228594d016229ed68c40088
        // const url = 'http://10.248.37.254:8802/azure/v1/download?resourceId='+resourceId;
        // const url = 'http://10.248.36.33:8004/cc.mp4';
        const url = 'http://10.248.37.36:8080/azure/v1/download/progress?resourceId=8a74819e6228594d0162298994ef0033';
        this.fileTransfer.download(url, this.file.dataDirectory + resourceId + '.mp4').then((entry) => {
            console.log('download complete: ' + entry.toURL());
            this.filePath = entry.toURL();
            this.now = 0;
            loading.dismiss();
        }, (error) => {
            // handle error
            this.now = 0;
            loading.dismiss();
        });
    }


    openJpegFile() {
        this.fileOpener.open(this.file.dataDirectory + this.mFileName, 'image/jpeg')
            .then(() => {
                console.log('Jpeg is opened!');
                this.filePath = '';
            })
            .catch(e => console.log('Jpeg open failed !', e));
    }

    openPdfFile() {
        // let fileUri = this.file.externalRootDirectory + 'plugindoc.pdf';
        // let fileUri = 'http://10.248.36.33:8004/' + 'plugindoc.pdf';
        this.fileOpener.open(this.file.dataDirectory + this.mFileName, 'application/pdf')
            .then(() => {
                console.log('Pdf is opened!');
                this.filePath = '';
            })
            .catch(e => console.log('Pdf open failed !', e));
    }

    openMP4File() {
        // let fileUri = this.file.externalRootDirectory + 'Touch_The_Sky.mp4';
        // let fileUri = 'http://10.248.36.33:8004/' + 'Touch_The_Sky.mp4';
        this.fileOpener.open(this.file.dataDirectory + this.mFileName, 'video/mp4')
            .then(() => {
                console.log('MP4 is opened!');
                this.filePath = '';
            })
            .catch(e => console.log('MP4 open failed !', e));
    }

    upLoadFile(fileName: string, mimeType: string) {
      this.fileService.saveFile(this.filePath, fileName, mimeType).subscribe(res => {
              console.log('up sssssssssssss');
              console.log(res)
          // this.resourceId = res;
      },
          error2 => {
              console.log('up ffffffffffff');
          });
    }

    getResourceFile() {
      this.fileService.getFile('8a74818a6223aee001622745dfe1003b','8a74818a6223aee001622745dfe1003b').subscribe(res => {
          console.log('get ssssssssss');
          console.log(res);
          let fileUrl = res.fileUrl;
          let mimeType = res.mimeType;
          console.log('fileUrl' + fileUrl);
          console.log('mineType' + mimeType);
          this.fileOpener.open(fileUrl, mimeType)
              .then(() => {
                  console.log('file is open success,fileUrl is : '+fileUrl + 'mimeType is : '+mimeType);
              })
              .catch(e => {
                  console.log('file is open failed,fileUrl is : '+fileUrl + 'mimeType is : '+mimeType, e);
              });
      },
          error2 => {
          console.log('get ffffffffffff');
          });
    }

    viewAttachFile(resourceId) {
        this.fileService.getFile(resourceId,resourceId).subscribe(res => {
                console.log('get ssssssssss');
                console.log(res);

                let fileUrl = res.fileUrl;
                let mimeType = res.mimeType;
                console.log('fileUrl' + fileUrl);
                console.log('mineType' + mimeType);
                this.fileOpener.open(fileUrl, mimeType)
                    .then(() => {
                        console.log('file is open success,fileUrl is : '+fileUrl + 'mimeType is : '+mimeType);
                    })
                    .catch(e => {
                        console.log('file is open failed,fileUrl is : '+fileUrl + 'mimeType is : '+mimeType, e);
                    });
            },
            error2 => {
                console.log('get file error', error2);
            });
    }
}
